<template>
	<view class="container">
		<!-- 页面头部 -->
		<view class="page-header">
			<view class="header-left" @click="goBack">
				<text class="back-icon">←</text>
				<text class="back-text">返回</text>
			</view>
			<text class="page-title">JSA创建</text>
			<view class="header-right">
				<text class="save-btn" @click="saveDraft">保存</text>
			</view>
		</view>
		
		<!-- 表单内容 -->
		<scroll-view class="form-scroll" scroll-y>
			<view class="form-container">
				<!-- 基本信息 -->
				<view class="form-section">
					<view class="section-title">
						<text class="title-text">基本信息</text>
					</view>
					
					<view class="form-item">
						<text class="label">JSA编号</text>
						<input class="input" v-model="formData.jsaNumber" disabled />
					</view>
					
					<view class="form-item">
						<text class="label">分析单位</text>
						<input class="input" v-model="formData.analysisUnit" placeholder="请输入分析单位" />
					</view>
					
					<view class="form-item">
						<text class="label">任务描述</text>
						<textarea class="textarea" v-model="formData.jobDescription" placeholder="请输入任务描述"></textarea>
					</view>
					
					<view class="form-item">
						<text class="label">工作位置</text>
						<input class="input" v-model="formData.workPosition" placeholder="请输入工作位置" />
					</view>
					
					<view class="form-item">
						<text class="label">工作时间段</text>
						<view class="date-range">
							<picker mode="multiSelector" :value="dateRangeIndex" :range="dateRangeData" @change="onDateRangeChange">
								<view class="picker-view">
									<text class="picker-text">{{ dateRangeText }}</text>
									<text class="picker-arrow">▼</text>
								</view>
							</picker>
						</view>
					</view>
					
					<view class="form-item">
						<text class="label">工作负责人</text>
						<picker :value="personInChargeIndex" :range="personnelList" range-key="name" @change="onPersonInChargeChange">
							<view class="picker-view">
								<text class="picker-text">{{ selectedPersonInCharge.name || '请选择工作负责人' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>
				
				<!-- 分析人员 -->
				<view class="form-section">
					<view class="section-title">
						<text class="title-text">分析人员</text>
					</view>
					
					<view class="personnel-list">
						<view 
							v-for="(person, index) in personnelList" 
							:key="index"
							class="personnel-item"
							@click="togglePersonnel(person.id)"
						>
							<view class="checkbox" :class="{ 'checked': formData.analyzers.includes(person.id) }">
								<text class="check-icon" v-if="formData.analyzers.includes(person.id)">✓</text>
							</view>
							<view class="personnel-info">
								<text class="personnel-name">{{ person.name }}</text>
								<text class="personnel-dept">{{ person.department }}</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 确认要求 -->
				<view class="form-section">
					<view class="section-title">
						<text class="title-text">确认要求</text>
					</view>
					
					<view class="confirm-options">
						<view class="option-item" @click="toggleConfirmer('analyzers')">
							<view class="checkbox" :class="{ 'checked': formData.confirmers.includes('analyzers') }">
								<text class="check-icon" v-if="formData.confirmers.includes('analyzers')">✓</text>
							</view>
							<text class="option-text">分析人员</text>
						</view>
						
						<view class="option-item" @click="toggleConfirmer('responsible_persons')">
							<view class="checkbox" :class="{ 'checked': formData.confirmers.includes('responsible_persons') }">
								<text class="check-icon" v-if="formData.confirmers.includes('responsible_persons')">✓</text>
							</view>
							<text class="option-text">措施责任人</text>
						</view>
						
						<view class="option-item" @click="toggleConfirmer('safety_officer')">
							<view class="checkbox" :class="{ 'checked': formData.confirmers.includes('safety_officer') }">
								<text class="check-icon" v-if="formData.confirmers.includes('safety_officer')">✓</text>
							</view>
							<text class="option-text">安全员</text>
						</view>
						
						<view class="option-item" @click="toggleConfirmer('supervisor')">
							<view class="checkbox" :class="{ 'checked': formData.confirmers.includes('supervisor') }">
								<text class="check-icon" v-if="formData.confirmers.includes('supervisor')">✓</text>
							</view>
							<text class="option-text">主管</text>
						</view>
					</view>
					
					<view class="form-item">
						<text class="label">确认截止时间</text>
						<picker mode="date" :value="formData.confirmDeadline" @change="onDeadlineChange">
							<view class="picker-view">
								<text class="picker-text">{{ formData.confirmDeadline || '请选择确认截止时间' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>
				
				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="btn btn-secondary" @click="saveDraft">保存草稿</button>
					<button class="btn btn-primary" @click="submitJSA">提交JSA</button>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					jsaNumber: '',
					analysisUnit: '',
					jobDescription: '',
					workPosition: '',
					workDateDuration: null,
					personInCharge: '',
					analyzers: [],
					confirmers: ['analyzers', 'responsible_persons'],
					confirmDeadline: ''
				},
				personInChargeIndex: 0,
				dateRangeIndex: [0, 0],
				dateRangeData: [[], []],
				personnelList: [
					{ id: '1', name: '张三', department: '维修部' },
					{ id: '2', name: '李四', department: '维修部' },
					{ id: '3', name: '王五', department: '安全部' },
					{ id: '4', name: '赵六', department: '生产部' }
				]
			}
		},
		computed: {
			selectedPersonInCharge() {
				return this.personnelList[this.personInChargeIndex] || {}
			},
			dateRangeText() {
				if (this.formData.workDateDuration) {
					return this.formData.workDateDuration
				}
				return '请选择工作时间段'
			}
		},
		onLoad() {
			this.initForm()
		},
		methods: {
			// 初始化表单
			initForm() {
				// 生成JSA编号
				this.formData.jsaNumber = this.generateJSANumber()
				
				// 初始化日期选择器数据
				this.initDateRangeData()
			},
			
			// 生成JSA编号
			generateJSANumber() {
				const now = new Date()
				const year = now.getFullYear()
				const month = String(now.getMonth() + 1).padStart(2, '0')
				const day = String(now.getDate()).padStart(2, '0')
				const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
				return `${year}-WELLTECH-TG-EM-${random}`
			},
			
			// 初始化日期范围数据
			initDateRangeData() {
				const dates = []
				const times = []
				
				// 生成未来7天的日期
				for (let i = 0; i < 7; i++) {
					const date = new Date()
					date.setDate(date.getDate() + i)
					dates.push(date.toLocaleDateString())
				}
				
				// 生成时间段
				for (let hour = 8; hour < 18; hour++) {
					times.push(`${hour.toString().padStart(2, '0')}:00`)
				}
				
				this.dateRangeData = [dates, times]
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 日期范围变化
			onDateRangeChange(e) {
				this.dateRangeIndex = e.detail.value
				const selectedDate = this.dateRangeData[0][e.detail.value[0]]
				const selectedTime = this.dateRangeData[1][e.detail.value[1]]
				this.formData.workDateDuration = `${selectedDate} ${selectedTime}`
			},
			
			// 工作负责人变化
			onPersonInChargeChange(e) {
				this.personInChargeIndex = e.detail.value
				this.formData.personInCharge = this.selectedPersonInCharge.id
			},
			
			// 截止时间变化
			onDeadlineChange(e) {
				this.formData.confirmDeadline = e.detail.value
			},
			
			// 切换分析人员
			togglePersonnel(personId) {
				const index = this.formData.analyzers.indexOf(personId)
				if (index > -1) {
					this.formData.analyzers.splice(index, 1)
				} else {
					this.formData.analyzers.push(personId)
				}
			},
			
			// 切换确认人员
			toggleConfirmer(type) {
				const index = this.formData.confirmers.indexOf(type)
				if (index > -1) {
					this.formData.confirmers.splice(index, 1)
				} else {
					this.formData.confirmers.push(type)
				}
			},
			
			// 保存草稿
			async saveDraft() {
				try {
					// 模拟API调用
					await new Promise(resolve => setTimeout(resolve, 1000))
					
					uni.showToast({
						title: '草稿保存成功',
						icon: 'success'
					})
				} catch (error) {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				}
			},
			
			// 提交JSA
			async submitJSA() {
				// 表单验证
				if (!this.validateForm()) {
					return
				}
				
				try {
					uni.showLoading({
						title: '提交中...'
					})
					
					// 模拟API调用
					await new Promise(resolve => setTimeout(resolve, 2000))
					
					uni.hideLoading()
					uni.showToast({
						title: 'JSA提交成功',
						icon: 'success'
					})
					
					// 跳转到JSA列表页面
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
					
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					})
				}
			},
			
			// 表单验证
			validateForm() {
				if (!this.formData.analysisUnit.trim()) {
					uni.showToast({
						title: '请输入分析单位',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.jobDescription.trim()) {
					uni.showToast({
						title: '请输入任务描述',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.workPosition.trim()) {
					uni.showToast({
						title: '请输入工作位置',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.personInCharge) {
					uni.showToast({
						title: '请选择工作负责人',
						icon: 'none'
					})
					return false
				}
				
				if (this.formData.analyzers.length === 0) {
					uni.showToast({
						title: '请选择分析人员',
						icon: 'none'
					})
					return false
				}
				
				if (this.formData.confirmers.length === 0) {
					uni.showToast({
						title: '请选择需要确认的人员',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.confirmDeadline) {
					uni.showToast({
						title: '请选择确认截止时间',
						icon: 'none'
					})
					return false
				}
				
				return true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f5f5;
	}
	
	.page-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		background: #fff;
		border-bottom: 1rpx solid #e4e7ed;
		
		.header-left {
			display: flex;
			align-items: center;
			
			.back-icon {
				font-size: 36rpx;
				color: #409EFF;
				margin-right: 10rpx;
			}
			
			.back-text {
				font-size: 32rpx;
				color: #409EFF;
			}
		}
		
		.page-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
		
		.header-right {
			.save-btn {
				font-size: 32rpx;
				color: #409EFF;
			}
		}
	}
	
	.form-scroll {
		flex: 1;
	}
	
	.form-container {
		padding: 30rpx;
	}
	
	.form-section {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		
		.section-title {
			margin-bottom: 30rpx;
			
			.title-text {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
	
	.form-item {
		margin-bottom: 30rpx;
		
		.label {
			display: block;
			font-size: 28rpx;
			color: #333;
			margin-bottom: 15rpx;
			font-weight: 500;
		}
		
		.input {
			width: 100%;
			height: 80rpx;
			border: 2rpx solid #e4e7ed;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 30rpx;
			background: #fff;
			box-sizing: border-box;
		}
		
		.textarea {
			width: 100%;
			min-height: 120rpx;
			border: 2rpx solid #e4e7ed;
			border-radius: 8rpx;
			padding: 20rpx;
			font-size: 30rpx;
			background: #fff;
			box-sizing: border-box;
		}
		
		.picker-view {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 80rpx;
			border: 2rpx solid #e4e7ed;
			border-radius: 8rpx;
			padding: 0 20rpx;
			background: #fff;
			
			.picker-text {
				font-size: 30rpx;
				color: #333;
			}
			
			.picker-arrow {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
	
	.personnel-list {
		.personnel-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.checkbox {
				width: 40rpx;
				height: 40rpx;
				border: 2rpx solid #e4e7ed;
				border-radius: 8rpx;
				margin-right: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				&.checked {
					background: #409EFF;
					border-color: #409EFF;
					
					.check-icon {
						color: #fff;
						font-size: 24rpx;
						font-weight: bold;
					}
				}
			}
			
			.personnel-info {
				flex: 1;
				
				.personnel-name {
					display: block;
					font-size: 30rpx;
					color: #333;
					margin-bottom: 5rpx;
				}
				
				.personnel-dept {
					display: block;
					font-size: 24rpx;
					color: #666;
				}
			}
		}
	}
	
	.confirm-options {
		.option-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.checkbox {
				width: 40rpx;
				height: 40rpx;
				border: 2rpx solid #e4e7ed;
				border-radius: 8rpx;
				margin-right: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				&.checked {
					background: #409EFF;
					border-color: #409EFF;
					
					.check-icon {
						color: #fff;
						font-size: 24rpx;
						font-weight: bold;
					}
				}
			}
			
			.option-text {
				font-size: 30rpx;
				color: #333;
			}
		}
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
		padding: 30rpx 0;
		
		.btn {
			flex: 1;
			height: 80rpx;
			border-radius: 12rpx;
			font-size: 32rpx;
			font-weight: bold;
			border: none;
			
			&.btn-secondary {
				background: #f0f0f0;
				color: #666;
			}
			
			&.btn-primary {
				background: #409EFF;
				color: #fff;
			}
		}
	}
</style>
